//
//  EntertainmentController.m
//  BobNews
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 YJC. All rights reserved.
//

#import "EntertainmentController.h"
#import "EntertainmentModel.h"
#import "EntertainmentCell.h"
#import "NetWorkRequestManager.h"
#import "ImageModelCell.h"
#import "MulModelCell.h"
#import "LORefresh.h"
#import "CycleView.h"
#import "EnterListViewController.h"
@interface EntertainmentController ()

@property (nonatomic,strong) NSMutableArray *entertainmentArray;
@property (nonatomic,strong) NSString *postid;
@property (nonatomic,strong) CycleView *cycleView;
@property (nonatomic,strong) NSString *start;
@end

@implementation EntertainmentController
- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.entertainmentArray = [NSMutableArray new];
    self.cycleView = [[CycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) interVal:2];
   [self.view addSubview:self.cycleView];
    self.start = @"10";
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.entertainmentArray = [NSMutableArray new];
    [self.tableView registerNib:[UINib nibWithNibName:@"ImageModelCell" bundle:nil] forCellReuseIdentifier:@"ImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MulModelCell" bundle:nil] forCellReuseIdentifier:@"MulImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CycleModelCell" bundle:nil] forCellReuseIdentifier:@"CycleModel"];
    
    [self loadData];
    [self loadCycle];
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.entertainmentArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadData];
    }];
    
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.entertainmentArray.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf loadData];
    }];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)loadCycle {
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:@"http://c.3g.163.com/nc/article/list/T1348648517839/0-40.html"] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = jsonDict[@"T1348648517839"];
            NSDictionary *listDict = dataArray[0];
            NSArray *adsArray = listDict[@"ads"];
            NSMutableArray *cycleArray = [NSMutableArray new];
            NSString *imsgesrc = listDict[@"imgsrc"];
            [cycleArray addObject:imsgesrc];
            for (NSDictionary *adsImgDict in adsArray) {
                NSString *imgsrc = adsImgDict[@"imgsrc"];
                [cycleArray addObject:imgsrc];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                self.cycleView.imgNameArray =cycleArray;
            });
        }
    }];
}

- (void)loadData {
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/T1348648517839/0-%@.html",self.start];
     [NetWorkRequestManager requestUrl:[NSURL URLWithString:url] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
         if (data) {
             NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
             NSArray *dataArray = jsonDict[@"T1348648517839"];
             for (NSDictionary *itemDict in dataArray) {
                 EntertainmentModel *model = [EntertainmentModel modelWithDictionary:itemDict];
                [self.entertainmentArray addObject:model];
             }
         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.tableView reloadData];
             [[self.tableView defaultHeader]endRefreshing];
             [[self.tableView defaultFooter]endRefreshing];
         });
     }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.entertainmentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [EntertainmentCell cellWithTableView:tableView Model:self.entertainmentArray[indexPath.row] indexPath:indexPath];
    return cell;

       // Configure the cell...
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EnterListViewController *enterVC = [[EnterListViewController alloc]init];
    enterVC.eModel = self.entertainmentArray[indexPath.row];
      [self.navigationController pushViewController:enterVC animated:YES];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
